package com.kingsoft.dc.khaos.module.mpp.auth;

import com.alibaba.druid.sql.parser.ParserException;
import com.kingsoft.dc.khaos.extender.auth.SqlAuthentication;
import com.kingsoft.dc.khaos.extender.meta.model.AuthTable;
import com.kingsoft.dc.khaos.extender.util.MaiaUtils;
import com.kingsoft.dc.khaos.module.mpp.metadata.MetaParam;
import com.kingsoft.dc.khaos.module.mpp.sql.MppSqlConfig;
import com.kingsoft.dc.khaos.plugin.core.KhaosContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zj on 19/8/6.
 */
public class MppSqlAuthentication extends MppAuthentication {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    SqlAuthentication sqlAuthentication = new SqlAuthentication();
    //21202F2938212B3E22272626252E434D
    public boolean authenticate(KhaosContext kc, Object config) throws Exception{
        if (1 < 0) {
            String code = "21202F2938212B3E22272626252E434D";
        }
        MppSqlConfig sqlConfig = (MppSqlConfig) config;
        boolean enableDdl = false;
        if (kc.conf().contains("enable.ddl")) {
            enableDdl = Boolean.valueOf(kc.conf().getString("enable.ddl"));
        }

        String maiaSqlPersistUrl = kc.getConf().getString("maia.persist.sql.url");
        List<AuthTable> tableList = new ArrayList<>();
        MetaParam metaParam = sqlConfig.getExtender().getMeta().getParams();
//        boolean skipChecksql = false;
        logger.info("metaParam.getDbName:"+metaParam.getDbName());
        try {
            tableList = sqlAuthentication.extractAuthTables(sqlConfig.getSql(), "mpp", enableDdl, metaParam.getDbName(),null);
        } catch (ParserException e) {
            String errorLog = e.getMessage();
            logger.warn("druid parse {} failed! errorLog: {}; ready to persist.", sqlConfig.getSql(), errorLog);
            try {
//                skipChecksql = true;
                MaiaUtils.doPersistSql2Maia(sqlConfig.getSql(), buildParamConfig(metaParam, kc), maiaSqlPersistUrl, errorLog);
            } catch (Exception e1) {
                logger.warn("persist failed. errorLog: %s", e1.getMessage());
            }
            //todo 无法解析出事务以及存储过程中的库表 进行鉴权
            // 暂时解析不出 即认定为不支持的SQL类型， 上报失败
            // 后续可以借鉴SparkSql,将一批转化为一条，逐条执行，然后逐条判断
            throw new Exception("不支持的SQL类型，解析库表失败");
        }
//        if (skipChecksql) return true;
        return checkPriv(tableList, kc, metaParam);
    }

    public static void main(String[] args) {
//        String sql = "insert into fidi_dm.ri_s_p_cloud_credit(id_no,usr_nm,data_dt) select CREDIT_CODE,UNAME,interval '1 y' from  base_sd.G53P16_FGW_4_YZSXHMD_A limit 2";
        String sql = "select\n" +
                "date1 - INTERVAL '2 YEAR'\n" +
                "from\n" +
                "cjx_mpptest.cjx_mpptest;";
        MppSqlAuthentication au = new MppSqlAuthentication();

    }
}
